package swb.api.com.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import swb.api.com.repository.WithdrawAccountRepository;
import swb.api.com.repository.WithdrawRecordRepository;
import swb.api.com.repository.dto.WithdrawAccount;
import swb.api.com.repository.dto.WithdrawRecord;
import swb.api.com.service.WithdrawService;
import swb.api.com.vo.resp.WithdrawResponse;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.Random;

@Service
@Transactional
public class WithdrawServiceImpl implements WithdrawService {

    @Autowired
    private WithdrawRecordRepository withdrawRecordRepository;

    @Autowired
    private WithdrawAccountRepository withdrawAccountRepository;

    @Override
    public WithdrawResponse applyWithdraw(Long userId, Long accountId, BigDecimal amount) {
        WithdrawResponse response = new WithdrawResponse();

        try {
            // 1. 验证账户信息
            WithdrawAccount account = validateAccount(userId, accountId);
            if (account == null) {
                response.setSuccess(false);
                response.setMessage("账户信息无效");
                return response;
            }

            // 2. 验证提现金额
            if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
                response.setSuccess(false);
                response.setMessage("提现金额必须大于0");
                return response;
            }

            // 3. 计算手续费和实际到账金额 (这里假设手续费为固定值，可根据业务调整)
            BigDecimal fee = calculateFee(amount);
            BigDecimal actualAmount = amount.subtract(fee);

            // 4. 创建提现记录
            WithdrawRecord record = new WithdrawRecord();
            record.setUserId(userId);
            record.setAccountId(accountId);
            record.setAmount(amount);
            record.setFee(fee);
            record.setActualAmount(actualAmount);
            record.setStatus(0); // 待处理
            record.setOutTradeNo(generateOutTradeNo());
            record.setCreatedAt(LocalDateTime.now());
            record.setUpdatedAt(LocalDateTime.now());

            // 5. 保存记录
            WithdrawRecord savedRecord = withdrawRecordRepository.save(record);

            response.setSuccess(true);
            response.setMessage("提现申请成功");
            response.setRecordId(savedRecord.getId());
            response.setOutTradeNo(savedRecord.getOutTradeNo());

        } catch (Exception e) {
            response.setSuccess(false);
            response.setMessage("提现申请失败: " + e.getMessage());
        }

        return response;
    }

    @Override
    public Page<WithdrawRecord> getWithdrawRecords(Long userId, Integer status, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());

        Page<WithdrawRecord> result;
        if (status != null) {
            result = withdrawRecordRepository.findByUserIdAndStatus(userId, status, pageable);
        } else {
            result = withdrawRecordRepository.findByUserId(userId, pageable);
        }

        // 返回总页数和总条数可以通过result.getTotalElements()和result.getTotalPages()获取
        // 但是由于方法签名限制，我们只能返回List<WithdrawRecord>
        // 总页数：result.getTotalPages()
        // 总条数：result.getTotalElements()
        
        return result;
    }

    @Override
    public WithdrawRecord getWithdrawRecordDetail(Long recordId) {
        return withdrawRecordRepository.findById(recordId).orElse(null);
    }

    @Override
    public WithdrawAccount getDefaultAccount(Long userId) {
        return withdrawAccountRepository.findByUserIdAndIsDefault(userId, 1).orElse(null);
    }

    /**
     * 验证账户有效性
     */
    private WithdrawAccount validateAccount(Long userId, Long accountId) {
        Optional<WithdrawAccount> accountOpt = withdrawAccountRepository
                .findByUserIdAndIdAndStatus(userId, accountId, 1);
        return accountOpt.orElse(null);
    }

    /**
     * 计算手续费 (可根据业务规则调整)
     */
    private BigDecimal calculateFee(BigDecimal amount) {
        // 假设手续费为金额的1%，最低2元
        BigDecimal feeRate = new BigDecimal("0.01");
        BigDecimal minFee = new BigDecimal("2.00");
        BigDecimal calculatedFee = amount.multiply(feeRate);
        return calculatedFee.compareTo(minFee) > 0 ? calculatedFee : minFee;
    }

    /**
     * 生成唯一的外部交易号
     */
    private String generateOutTradeNo() {
        return "WD" + System.currentTimeMillis() +
                String.format("%06d", new Random().nextInt(999999));
    }
}
